﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Net;
using System.IO;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;


namespace NetMonitor.Server
{
    public partial class SrvForm : Form
    {
        public SrvForm()
        {
            InitializeComponent();            

            TcpServerChannel channel = new TcpServerChannel(6666);
            ChannelServices.RegisterChannel(channel, false);
            RemotingConfiguration.RegisterWellKnownServiceType(typeof(NetMonServer), "NetMonSrv", WellKnownObjectMode.Singleton);
        }


        /// <summary>
        /// 定义一个pool，容纳所有节点
        /// </summary>
        public static List<NetPoint> NetNodes = new List<NetPoint>();

        // lryh 直接保存配置文件
        private static string config = "";
        public static string Config
        {
            get { return config; }
            set 
            { 
                clear();
                open(new StringReader(value)); 
            }
        }

        private static void clear()
        {
            config = "";                        
            NetNodes.Clear();
        }

        private static void open(TextReader sr)
        {
            string[] tokens;
            string Line, id, name, location, ip;
            int j, x, y, pointtype, img = 0;
            //读取节点信息
            while ((Line = sr.ReadLine()) != null)
            {
                tokens = Line.Split(' ');
                if (tokens.Length > 1)
                {
                    j = 0;
                    id = "";
                    if (tokens[j].IndexOf("(") == 0)
                    {
                        string temp = tokens[j++];
                        id = temp.Substring(1, temp.Length - 2);
                    }
                    name = tokens[j++];
                    location = tokens[j++];
                    ip = tokens[j++];
                    pointtype = Convert.ToInt32(tokens[j++]);

                    if (tokens[j].IndexOf("(") == 0)
                    {
                        string temp = tokens[j++];
                        img = Convert.ToInt32(temp.Substring(1, temp.Length - 2));
                    }

                    string xy = tokens[j++];
                    x = Convert.ToInt32(xy.Substring(xy.IndexOf("X=") + 2, xy.IndexOf(',') - (xy.IndexOf("X=") + 2)));
                    y = Convert.ToInt32(xy.Substring(xy.IndexOf("Y=") + 2, xy.IndexOf('}') - (xy.IndexOf("Y=") + 2)));

                    NetPoint node = new NetPoint();
                    node.ID = id;
                    node.PointName = name;
                    node.PointLocation = location;
                    node.PointIpaddress = IPAddress.Parse(ip);
                    node.PointType = pointtype;
                    node.PointPosition = new Point(x, y);
                    node.ImgGroup = img;
                    node.Neighbors = "";
                    while (j < tokens.Length)
                    {
                        if (tokens[j].Length > 0)                    
                            node.Neighbors += tokens[j] + " ";
                        j++;
                    }

                    NetNodes.Add(node);

                    config += Line + "\r\n";
                }
            }
        }


        private void refreshNodes()
        {
            listView1.Items.Clear();

            int i = 0;
            foreach (NetPoint n in NetNodes)
            {
                ListViewItem li = new ListViewItem();
                li.Tag = n;
                li.SubItems.Clear();               
                li.SubItems[0].Text = n.PointName;
                li.UseItemStyleForSubItems = false;
                li.SubItems.Add(n.PointIpaddress.ToString());
                string s = n.Connectivity;
                var sub = li.SubItems.Add(s);
                if (s == "warning")
                {
                    sub.ForeColor = Color.Orange;
                }
                else if (s == "alarm")
                {
                    sub.ForeColor = Color.Red;
                }
                else if (s == "normal")
                {
                    sub.ForeColor = Color.Blue;
                }                               
                listView1.Items.Add(li);
            
            }
        }
        

        private void saveToDb()
        {
            using (DataClasses1DataContext dc = new DataClasses1DataContext())
            {                
                foreach (NetPoint n in NetNodes)
                {
                    if (n.ID != null && n.ID.Length > 0)
                    {
                        var nodes = from node in dc.NetNode where node.Id == Convert.ToInt32(n.ID) select node;       
                        if (nodes.ToList().Count > 0)
                            return;
                    }
                                          
                    var newNode = new NetNode
                    {
                        PointName = n.PointName,
                        PointLocation = n.PointLocation,
                        PointIpaddress = n.PointIpaddress.ToString(),
                        PointType = n.PointType,
                        ImgGroup = n.ImgGroup,
                        Coordinate_X = n.PointPosition.X,
                        Coordinate_Y = n.PointPosition.Y
                    };
                    dc.NetNode.InsertOnSubmit(newNode);
                    dc.SubmitChanges();

                    n.ID = "" + newNode.Id;                    
                }
            }
        }

        private void saveConfig(string filename)
        {
            if (filename != null && filename.Length > 0)
            {
                config = "";

                File.WriteAllText(filename, "");
                FileStream f = File.Open(filename, FileMode.OpenOrCreate);
                StreamWriter MySW = new StreamWriter(f);
                try
                {
                    foreach (NetPoint n in NetNodes)
                    {
                        string line = "";
                        if (n.ID != null && n.ID.Length > 0)
                            line += "(" + n.ID + ") ";
                        line += n.PointName + " " + n.PointLocation + " " + n.PointIpaddress + " " + n.PointType + " ";
                        line += "(" + n.ImgGroup + ") " + n.PointPosition + " " + n.Neighbors;
                        
                        config += line + "\r\n";
                        MySW.WriteLine(line);
                    }

                    MySW.Flush();
                    MySW.Close();                    
                }
                catch (Exception ex)
                {
                    MessageBox.Show("保存文本文件失败！" + ex.Message.ToString());
                }
            }
        }

        private void menuOpen_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                clear();

                try
                {                    
                    Stream myStream1 = openFileDialog1.OpenFile();
                    if ((myStream1) != null)
                    {                        
                        StreamReader sr = new StreamReader(myStream1);
                        //读取节点信息
                        open(sr);
                        sr.Close();
                        myStream1.Close();

                        saveToDb();
                        saveConfig(openFileDialog1.FileName);
                        refreshNodes();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    System.Console.Out.WriteLine(ex.StackTrace);
                }
            }
        }

        
        /// <summary>
        /// 每一个时间间隔实现一次轮训
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {            
            foreach (NetPoint node in NetNodes)                                    
                node.StartPing();                
        }

        private void button1_Click(object sender, EventArgs e)
        {
            timer1.Start();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            refreshNodes();
            /*
            textBox1.Clear();
            foreach (NetPoint node in NetNodes)
            {
                string s = "" + node.ID + " | " + node.PointName + "(" + node.PointIpaddress + ")" + " : " + node.Connectivity;                
                textBox1.Text += s + "\r\n";

            }*/
            
        }

        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
            {
                radioButton1.Enabled = true;
                radioButton2.Enabled = true;
                radioButton3.Enabled = true;
                radioButton4.Enabled = true;

                ListViewItem li = listView1.SelectedItems[0];
                NetPoint np = li.Tag as NetPoint;
                if (li.SubItems.Count > 3)
                {
                    if (li.SubItems[3].Text == "Normal")
                        radioButton1.Checked = true;
                    else if (li.SubItems[3].Text == "Warning")
                        radioButton2.Checked = true;
                    else if (li.SubItems[3].Text == "Alarm")
                        radioButton3.Checked = true;
                }
                else
                {
                    if (np.CustomStatus == null)
                        radioButton4.Checked = true;
                    else if (np.CustomStatus == "normal")
                        radioButton1.Checked = true;
                    else if (np.CustomStatus == "warning")
                        radioButton2.Checked = true;
                    else if (np.CustomStatus == "alarm")
                        radioButton3.Checked = true;                    
                }
            }
        }

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
            {
                ListViewItem li = listView1.SelectedItems[0];
                if (li.SubItems.Count > 3)
                {
                    if (radioButton4.Checked)
                        li.SubItems[3].Text = "Default";
                    else if (radioButton1.Checked)
                        li.SubItems[3].Text = "Normal";
                    else if (radioButton2.Checked)
                        li.SubItems[3].Text = "Warning";
                    else if (radioButton3.Checked)
                        li.SubItems[3].Text = "Alarm";
                }
                else
                {
                    NetPoint np = li.Tag as NetPoint;
                    if (radioButton4.Checked)
                    {
                        if (np.CustomStatus != null) 
                            li.SubItems.Add("Default");
                    }
                    else if (radioButton1.Checked)
                    {
                        if (np.CustomStatus != "normal")
                            li.SubItems.Add("Normal");
                    }
                    else if (radioButton2.Checked)
                    {
                        if (np.CustomStatus != "warning")
                            li.SubItems.Add("Warning");
                    }
                    else if (radioButton3.Checked)
                    {
                        if (np.CustomStatus != "alarm")
                            li.SubItems.Add("Alarm");
                    }                    
                }
                
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem li in listView1.Items)
            {
                NetPoint np = li.Tag as NetPoint;
                if (li.SubItems.Count > 3)
                {
                    if (li.SubItems[3].Text == "Default")
                        np.CustomStatus = null;
                    else
                        np.CustomStatus = li.SubItems[3].Text.ToLower();
                }
            }
            refreshNodes();
        }

                
    }
}
